// 如非树莓派环境调试，可以注释本代码中与具名管道相关的内容。8887端口如果有其他服务可以更换端口。

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/shm.h>
#include <sys/wait.h>

#include <signal.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <fcntl.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <errno.h>

#define ServerPort 8887
#define Queue 20
#define BufferSize 1024

int childrenPid[30];

void checkExit(int signal){
    int i;
    for(i=0;i<30;i++) kill(childrenPid[i],SIGKILL);
    exit(0);
}

int main(){
    // 具名管道通信相关变量
    char writeFifoName[] = "ledFifo";
    int writeFd;
    if((writeFd = open(writeFifoName, O_WRONLY)) == -1){
        printf("Fail to open FIFO %s: %s",writeFifoName,strerror(errno));
        exit(1);
    }

    // socket通信相关变量
    int serverSocketFd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in serverSocketAddr;
    serverSocketAddr.sin_family = AF_INET;
    serverSocketAddr.sin_port = htons(ServerPort);
    serverSocketAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(serverSocketFd,(struct sockaddr*)&serverSocketAddr,sizeof(serverSocketAddr))==-1){
        perror("Bind error");
        exit(1);
    }

    if(listen(serverSocketFd,Queue)==-1){
        perror("Listen error");
        exit(1);
    }

    char control[10];
    struct sigaction action;
    int status;
    int cnt = 0;

    char buffer[BufferSize];
    struct sockaddr_in clientSocketAddr;
    socklen_t len = sizeof(clientSocketAddr);

    pid_t pid = fork();

    if(pid){
        // 父进程用于输入相应的控制信号
        // exit ---- 杀死子进程及其所有子进程并退出
        // esc  ---- 强制退出子进程，不对其子进程做处理
        sleep(1);
        while(0 == waitpid(pid,&status,WNOHANG)){
            scanf("%s",control);
            if(strncmp(control, "esc", 4)==0){
                kill(pid,SIGKILL);
                break;
            } else if(strncmp(control, "exit", 5)==0){
                kill(pid,SIGTERM);
                write(writeFd, "exit", 5);
                break;
            }
        }
    } else {
        action.sa_handler = checkExit;
        sigemptyset(&action.sa_mask);
        sigaction(SIGTERM, &action, 0);
        // 子进程用于分裂新的进程进行通信，每一次有新的连接就分裂出新的子进程，使服务端可以进行一对多的通信
        loop: ;
        int connect = accept(serverSocketFd, (struct sockaddr*)&clientSocketAddr, &len);
        if(connect<0){
            perror("Accept error");
            exit(1);
        }
        pid_t ppid = fork();
        if(ppid){ 
            childrenPid[cnt++] = ppid;
            goto loop;
        }
        printf("%d: 客户端接入\n", getpid());
        while(1){
            memset(buffer,0,sizeof(buffer));
            // 接收来自客户端的buffer
            int len = recv(connect, buffer, sizeof(buffer), 0);
            if(strncmp(buffer, "exit", 4)==0) {
                printf("%d: %s", getpid(), "客户端退出\n");
                break;
            }
            printf("%d: %s", getpid(), buffer);
            // 将客户端的buffer通过具名管道发送到三色灯控制进程
            // 给客户端回应收到
            write(writeFd, buffer, strlen(buffer));
            send(connect,"Server Get\n",12,0);
        }
    }
    return 0;
}